package demo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflexDemo {
    public static void main(String[] args) {
        try {
           Class person= Class.forName("demo.Person");
            System.out.println(person+":"+person.getName());
            //反射类中的所有方法(公有/私有)
            Method[] methods=person.getDeclaredMethods();
            for (Method method:methods
                 ) {
                System.out.println(method.getName());
            }
            //反射类中的公有方法
            Method method=person.getMethod("getAge",null);
            Object obj=person.newInstance();
            method.invoke(obj,null);
            //反射类中的所有公有构造方法
            Constructor[]constructors=person.getConstructors();
            for (Constructor constructor:constructors
                 ) {
                System.out.println(constructor);
            }
            //反射类中公有无参构造方法
            Constructor c=person.getConstructor(null);
            c.newInstance(null);
            //反射类中公有有参构造方法
            Constructor c1=person.getConstructor(String.class,String.class,String.class,String.class,int.class);
            c1.newInstance("李浩","河北","个体户","121212121212",30);
            //反射类中私有有参构造方法
            Constructor c2=person.getDeclaredConstructor(int.class);
            c2.setAccessible(true);
            c2.newInstance(35);
            //反射类中所有属性(公有/私有)
            Field[] fields=person.getDeclaredFields();
            for (Field field:fields
                 ) {
                System.out.println(field.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
